package com.itheima.common;

import com.itheima.mapper.OperatorLogMapper;
import com.itheima.pojo.OperatorLog;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Date;

@Component
@Slf4j
@Aspect
public class LogAspect {

    @Autowired
    private OperatorLogMapper operatorLogMapper;


    @Around("@annotation(com.itheima.anno.Log)")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {

        //操作时间
        Date date = new Date();
        //操作方法名
        String methodName = joinPoint.getSignature().getName();
        //操作方法参数
        Object[] args = joinPoint.getArgs();
        String methodParams = Arrays.toString(args);
        //调用原始目标方法运行
        long begin = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long end = System.currentTimeMillis();

        //操作耗时
        long cost = end - begin;
        //记录操作日志

        OperatorLog operateLog = new OperatorLog(null,methodName, methodParams, cost,date);
        operatorLogMapper.addLog(operateLog);
        log.info("AOP记录操作日志：{}", operateLog);
        return result;
    }

}
